package com.xerland.tbootstrap.ui.presenters;

import android.content.Context;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xerland.tbootstrap.core.mqtt.MqttHelper;
import com.xerland.tbootstrap.model.PowerStateBean;
import com.xerland.tbootstrap.model.RealTimeData;
import com.xerland.tbootstrap.ui.ExpandableListViewFragment;
import com.xerland.tbootstrap.ui.base.BasePresenter;
import com.xerland.tbootstrap.ui.views.ExpandableListViewFragmentView;
import com.xerland.tbootstrap.utils.SpfManager;
import com.xerland.tbootstrap.utils.TopicFormater;

import java.lang.reflect.Type;
import java.util.List;

import timber.log.Timber;

/**
 * Fileame: com.xerland.tbootstrap.core.mqtt
 * Desription:
 * Class and methods:
 * @Topic subscription and publish format: Destination@Topic@Source
 * @Destination and Source format: Prefix+UserID
 * @Topic format: baseTopic+extra
 * @Public VS Private topic: Topic@Source VS Destination@Topic@Source
 * @Reactive Extra Topic: content/request VS content/response
 * Author: Anson Chan
 * Copyright: 2016 Xerland Co. Ltd. All rights reserved.
 * Contact:    anson_chan@xerland.com
 * Deffield    updated: Updated
 */
public class MqttPresenter extends BasePresenter<ExpandableListViewFragmentView> {

    final String userPrefix = "/user/";
    final String userTopicDevider = "@";
    final String subscriptionTopic = "/saibao/led/#";
    final String baseSubscription = "/saibao/led/#";
    final String rtdUpdateSubscription = "/saibao/led/rtd/update";
    final String powerUpdateSubscription = "/saibao/led/powerstate/update";
    final String rtdResponseSubscription = "/saibao/led/rtd/response";
    final String powerResponseSubscription = "/saibao/led/powerstate/response";
    final String rtdRequestPublish = "/saibao/led/rtd/request";
    final String powerRequestPublish = "/saibao/led/powerstate/request";

    private String userId;
    private String providerId;
    private String rtdUpdateSub;
    private String powerUpdateSub;
    private String rtdResponseSub;
    private String powerRequestPub;
    private String powerResponseSub;
    private String rtdRequestPub;

    private MqttHelper mqttHelper;
    private ExpandableListViewFragment expandableListViewFragment;
    private TopicFormater topicFormater;

//    public MqttPresenter

    public MqttPresenter(Context context) {
        mqttHelper = new MqttHelper(context);
        SpfManager spfManager = new SpfManager(context);
        userId = userPrefix + spfManager.loadUserId();
        providerId = userPrefix + spfManager.loadPeerId();
        Timber.e("providerId is %s .............", providerId);
//        rtdUpdateSub = spfManager.loadBaseTopic() + "/rtd/update";    //+"@"+providerId
//        powerUpdateSub = spfManager.loadBaseTopic() + "/powerstate/update";  //+"@"+providerId
//        rtdResponseSub = userId + userTopicDevider + spfManager. loadBaseTopic() + "/rtd/response";
//        powerRequestPub = providerId + userTopicDevider + spfManager.loadBaseTopic() + "/powerstate/request";
//        powerResponseSub = userId + userTopicDevider + spfManager.loadBaseTopic() + "/powerstate/response";
//        rtdRequestPub = providerId + userTopicDevider + spfManager.loadBaseTopic() + "/rtd/request";

//        if (!rtdUpdateSub.equals(rtdUpdateSubscription)) {
//            Timber.e("%s not equal!", rtdUpdateSubscription);
//        }
//        if (!powerUpdateSub.equals(powerUpdateSubscription)) {
//            Timber.e("%s not equal", powerUpdateSubscription);
//        }
//        if (!rtdResponseSub.equals(MqttHelper.clientId+"@"+rtdResponseSubscription)) {
//            Timber.e("%s not equal",rtdResponseSub);
//        }
//        if (!powerResponseSub.equals(MqttHelper.clientId+"@"+powerResponseSubscription)) {
//            Timber.e("%s vs %s", powerResponseSub, MqttHelper.clientId+"@"+powerResponseSubscription);
//        }
//        if (!powerRequestPub.equals(powerRequestPublish+"@"+MqttHelper.clientId)) {
//            Timber.e("%s not equal", powerRequestPub);
//        }
//        if (!rtdRequestPub.equals(rtdRequestPublish)) {
//            Timber.e("%s not equal", rtdRequestPub);
//        }
        Timber.e("..................................................................................");
        topicFormater = new TopicFormater(context);
        Timber.e(topicFormater.getSubFrom("/powerstate/update"));
        Timber.e(topicFormater.getSubFrom("/rtd/update"));
        Timber.e(topicFormater.getSubToFromX("/powerstate"));
        Timber.e(topicFormater.getSubToFromX("/rtd"));
        Timber.e(topicFormater.getPubToFromX("/powerstate"));
        Timber.e(topicFormater.getPubToFromX("/rtd"));
//        bindTopicHandler();
    }

    public void bindTopicHandler(ExpandableListViewFragment expandableListViewFragment) {
        this.expandableListViewFragment = expandableListViewFragment;

        if (topicFormater == null) {
            Timber.e("topicFormater is null");
        }
        if (topicFormater.getSubFrom("/rtd/update") == null) {
            Timber.e("topicFormater get is null");
        }
        mqttHelper.setTopicHandler(topicFormater.getSubFrom("/rtd/update"), new MqttHelper.TopicHandler() {
            @Override
            public void run(String topic, String payload) {
//                expandableListViewFragment.updateListViewWithRtdList(null);
                Timber.e(payload);
                Gson g = new Gson();
                Type lt=new TypeToken<List<RealTimeData>>(){}.getType();
                List<RealTimeData> realTimeDataList = g.fromJson(payload, lt);
                expandableListViewFragment.updateListViewWithRtdList(realTimeDataList, false);
            }
        });

        mqttHelper.setTopicHandler(topicFormater.getSubFrom("/powerstate/update"), new MqttHelper.TopicHandler() {
            @Override
            public void run(String topic, String payload) {
                Gson g = new Gson();
                Type lt=new TypeToken<List<PowerStateBean>>(){}.getType();
                List<PowerStateBean> powerStateBeanList = g.fromJson(payload, lt);
                Timber.e("do update!");
                expandableListViewFragment.updateListViewWithPowerStateList(powerStateBeanList);
            }
        });

        mqttHelper.setTopicHandler(topicFormater.getSubToFromX("/rtdpage"), new MqttHelper.TopicHandler() {
            @Override
            public void run(String topic, String payload) {
//                Todo: do rtd history handling if on request
                Timber.e(payload);
                Gson g = new Gson();
                Type lt=new TypeToken<List<RealTimeData>>(){}.getType();
                List<RealTimeData> realTimeDataList = g.fromJson(payload, lt);
                expandableListViewFragment.updateListViewWithRtdList(realTimeDataList, true);
            }
        });

        mqttHelper.setTopicHandler(topicFormater.getSubToFromX("/powerstate"), new MqttHelper.TopicHandler() {
            @Override
            public void run(String topic, String payload) {
                Timber.e("recv power state response!");
                Timber.e(payload);
                Gson g = new Gson();
//                PowerStateBean powerStateBean = new PowerStateBean();
                Type lt=new TypeToken<List<PowerStateBean>>(){}.getType();
                List<PowerStateBean> powerStateBeanList = g.fromJson(payload, lt);
                Timber.e("recv power state list length is:" + powerStateBeanList.size());
                expandableListViewFragment.updateListViewWithPowerStateList(powerStateBeanList);
            }
        });

    }

    public void start() {
        mqttHelper.setPublishAfterSubscription(topicFormater.getPubToFromX("/powerstate"), "[]");
        mqttHelper.connect();
    }

    public void stop() {
        mqttHelper.close();
        mqttHelper.release();
        mqttHelper = null;
    }

//    For test purpose
    public void getMachList() {
        Timber.e("do getMachList!");
        mqttHelper.publishMessage(topicFormater.getPubToFromX("/powerstate"), "[]");
    }

    public void getHistoryPage(PowerStateBean powerStateBean) {
        Timber.e("do getHistoryPage!");
        Timber.e("historyPageReq:%s", powerStateBean.toJson());
        mqttHelper.publishMessage(topicFormater.getPubToFromX("/rtdpage"), powerStateBean.toJson());
    }

}
